<template>
  <div class="image-lazy-box">
    <img
      :src="displaySrc"
      :fit="fit"
      :style="imgStyle"
      @load="imageLoadComplete"
    />
  </div>
</template>

<script>
import defaultLoadingImg from "./1.gif";
import { on, off } from "./domUtils.js";
export default {
  props: {
    index: {
      type: Number,
      default: 0,
    },
    // 图片资源
    baseUrl: {
      type: [String, Object],
      default: "",
    },
    // 图片填充模式
    fit: {
      type: String,
      default: "none",
    },
    // 图片样式
    imgStyle: {
      type: String,
      default: "",
    },
    scrollParent: {
      default: () => null,
    },
  },
  components: {},
  data() {
    return {
      defaultLoadingImg,
      isLoading: true,
      isLazy: true,
      eventExist: false,
      scrollParentCopy: null,
    };
  },
  created() {},
  mounted() {
    this.initLazy();
    if (this.eventExist) {
      this.onScrollChange();
    }
  },
  beforeDestroy() {
    if (this.eventExist) this.bindEventOff();
  },
  computed: {
    displaySrc: (vm) =>
      !vm.isLazy && !vm.isLoading ? vm.baseUrl : defaultLoadingImg,
  },
  watch: {},
  methods: {
    imageLoadComplete() {
      console.log("完成");
      this.isLoading = false;
    },

    initLazy() {
      const scrollParent = this.scrollParent;
      if (!scrollParent) return;
      this.scrollParentCopy = scrollParent;
      this.bindEventOn();
    },
    onScrollChange() {
      const el = this.$el;
      const scrollParentCopy = this.scrollParentCopy;
      const top = this.getOffsetTop(el);
      if (top - scrollParentCopy.scrollTop <= scrollParentCopy.offsetHeight) {
        this.isLazy = false;
        if (this.eventExist) {
          this.bindEventOff();
        }
      }
    },
    getOffsetTop(el) {
      let top = el.offsetTop;
      let current = el.offsetParent;
      const scrollParentCopy = this.scrollParentCopy;

      while (current !== null && !current.isSameNode(scrollParentCopy)) {
        top += current.offsetTop;
        current = current.offsetParent;
      }
      return top;
    },
    bindEventOn() {
      const scrollParentCopy = this.scrollParentCopy;
      if (!scrollParentCopy) return;
      on(scrollParentCopy, "scroll", this.onScrollChange);
      this.eventExist = true;
    },
    bindEventOff() {
      const scrollParentCopy = this.scrollParentCopy;
      if (!scrollParentCopy) return;
      off(scrollParentCopy, "scroll", this.onScrollChange);
      this.eventExist = false;
    },
  },
};
</script>

<style lang="less"></style>

<style lang="less" scoped>
.image-lazy-box {
  width: 100%;
  height: 100%;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
